package com.diyizu.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diyizu.youdianda.common.R;
import com.diyizu.youdianda.dto.SysUserDto;
import com.diyizu.youdianda.dto.SysUserPage;
import com.diyizu.youdianda.entity.SysRole;
import com.diyizu.youdianda.entity.SysUser;
import com.diyizu.youdianda.service.SysRoleService;
import com.diyizu.youdianda.service.SysUserService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys_user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/list")
    public R getList(String login_name,String status,String phone,int page,int limit){

        //查询构造器
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        if (Strings.isNotEmpty(status)){
            lqw.eq(SysUser::getStatus,Integer.parseInt(status));
        }
        lqw.eq(Strings.isNotEmpty(phone),SysUser::getPhone,phone);
        lqw.like(Strings.isNotEmpty(login_name),SysUser::getLoginName,login_name);

        //分页构造器
        Page<SysUser> pageInfo = new Page<>(page, limit);
        sysUserService.page(pageInfo,lqw);
        if (page!=1&&pageInfo.getRecords().size()==0){
            pageInfo = new Page<>(page-1, limit);
            sysUserService.page(pageInfo,lqw);
        }

        SysUserPage sysUserPage = new SysUserPage();
        sysUserPage.setCount((int) pageInfo.getTotal());
        sysUserPage.setTotalPages((int) pageInfo.getPages());
        sysUserPage.setPageSize(limit);
        sysUserPage.setCurrentPage(page);

        List<SysUserDto> sysUserDtos = pageInfo.getRecords().stream().map(item -> {
            SysUserDto sysUserDto = new SysUserDto();
            BeanUtils.copyProperties(item, sysUserDto, "roleId");

            String roleId = item.getRoleId();
            String substring = roleId.substring(2, roleId.length() - 2);
            String[] split = substring.split("\",\"");
            sysUserDto.setRole_id(split);

            ArrayList<String> list = new ArrayList<>();
            for (String s : split) {
                SysRole role = sysRoleService.getById(s);
                list.add(role.getName());
            }
            sysUserDto.setRolename(list);

            return sysUserDto;
        }).collect(Collectors.toList());


        sysUserPage.setData(sysUserDtos);
        return R.success(sysUserPage);
    }

    @GetMapping("/del")
    public R getDel(String id){
        sysUserService.removeById(id);
        return R.success("管理员删除成功");
    }

    @PostMapping("/add")
    public R add(@RequestBody SysUserDto sysUserDto){
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getLoginName,sysUserDto.getLoginName());
        SysUser user = sysUserService.getOne(lqw);
        if (user!=null){
            return R.error("用户名已存在");
        }


        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto,sysUser,"password");


        String[] role_id = sysUserDto.getRole_id();
        String roleIds="[\"";
        for (int i = 0;i<role_id.length;i++) {
            if (i<role_id.length-1){
                roleIds=roleIds+role_id[i]+"\",\"";
            }else {
                roleIds=roleIds+role_id[i]+"\"]";
            }
        }

        sysUser.setRoleId(roleIds);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserDto.getPassword().getBytes()));
        sysUserService.save(sysUser);
        return R.success("管理员添加成功");
    }

    @GetMapping("/rowInfo")
    public R rowInfo(String id){
        SysUser sysUser = sysUserService.getById(id);

        String roleId = sysUser.getRoleId();
        String substring = roleId.substring(2, roleId.length() - 2);
        String[] split = substring.split("\",\"");
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser,sysUserDto,"roleId");
        sysUserDto.setRole_id(split);

        return R.success(sysUserDto);
    }

    @PostMapping("/update")
    public R update(@RequestBody SysUserDto sysUserDto){
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto,sysUser,"password");
        //处理role_id
        if (sysUserDto.getRole_id()!=null){
            String[] role_id = sysUserDto.getRole_id();
            String roleIds="[\"";
            for (int i = 0;i<role_id.length;i++) {
                if (i<role_id.length-1){
                    roleIds=roleIds+role_id[i]+"\",\"";
                }else {
                    roleIds=roleIds+role_id[i]+"\"]";
                }
            }
            sysUser.setRoleId(roleIds);
        }

        //处理password
        if (Strings.isNotEmpty(sysUserDto.getPassword())){
            String password = DigestUtils.md5DigestAsHex(sysUserDto.getPassword().getBytes());
            sysUser.setPassword(password);
        }
        //更新
        sysUserService.updateById(sysUser);
        return R.success("管理员更新成功");
    }


}
